package cn.itcast.diy.springreadxml;

import cn.itcast.service.entity.BeanDefinition;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义的spring beans  解析程序
 * Created by zkr on 2018/5/27.
 */
public class ItcastClassPathXMLApplicationContext {

    private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();
    private Map<String,Object> sigletons = new HashMap<String,Object>();

    public ItcastClassPathXMLApplicationContext(String filename){

        this.readXML(filename);
        this.instanceBeans();

    }

    private void instanceBeans() {

        for (BeanDefinition beanDefinition:beanDefinitions){
            try {
                sigletons.put(beanDefinition.getId(),Class.forName(beanDefinition.getClassName()).newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 读取配置xml文件
     * @param filename
     */
    private void readXML(String filename){

        SAXReader saxReader = new SAXReader();
        Document document = null;

        try {
            URL xmlpath = this.getClass().getClassLoader().getResource(filename);
            document = saxReader.read(xmlpath);
            Map<String,String> nsMap = new HashMap<String,String>();
            nsMap.put("ns","http://www.springframework.org/schema/beans"); //加入命名空间
            XPath xsub = document.createXPath("//ns:beans/ns:bean"); //创建beans/bean的查询路径
            xsub.setNamespaceURIs(nsMap); //设置命名空间
            List<Element> beans = xsub.selectNodes(document); //获取文档下所有bean节点
            for (Element element:beans){

                String id = element.attributeValue("id");  //获取id属性值
                String clazz = element.attributeValue("class"); // 获取class属性值
                BeanDefinition beanDefinition = new BeanDefinition(id,clazz);
                beanDefinitions.add(beanDefinition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取bean实例
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){

        return this.sigletons.get(beanName);
    }



}
